<template>
  <el-scrollbar class="horizontal-scrollbar" wrap-class="scroll-wrapper">
    <div class="box">
      <el-tabs v-model="activeTab">
        <el-tab-pane label="订单详情" name="detail">
          <el-row v-if="windowWidth > 1680">
            <el-col :span="12">
              <Process />
            </el-col>
            <el-col :span="12">
              <Order />
              <Cert />
            </el-col>
          </el-row>
          <el-row v-else>
            <el-col :span="24">
              <Process />
              <Order />
              <Cert />
            </el-col>
          </el-row>
        </el-tab-pane>
        <el-tab-pane label="颁发记录" name="issueList">
          <IssueList :active-tab="activeTab" />
        </el-tab-pane>
      </el-tabs>
    </div>
  </el-scrollbar>
</template>
<script setup lang="ts">
import {
  ref,
  provide,
  reactive,
  onMounted,
  onUnmounted,
  onBeforeUnmount,
  toRefs
} from "vue";
import { buildUUID } from "@pureadmin/utils";
import Process from "./components/process.vue";
import Cert from "./components/cert.vue";
import Order from "./components/order.vue";
import IssueList from "./components/issueList.vue";
import * as OrderApi from "@/api/order";
import { message } from "@/utils/message";

const activeTab = ref("detail");

const props = defineProps(["modelValue"]);

const order = reactive(props.modelValue);
provide("order", order);

const { latest_cert: cert } = toRefs(order);
provide("cert", cert);

const sync = (notification = false) => {
  OrderApi.sync(order.id).then(() => {
    OrderApi.show(order.id).then(res => {
      res.data.sync = buildUUID();
      Object.assign(order, reactive(res.data));
      notification && message("同步成功", { type: "success" });
    });
  });
};
const get = (notification = false) => {
  OrderApi.show(order.id).then(res => {
    res.data.sync = buildUUID();
    Object.assign(order, reactive(res.data));
    notification && message("刷新成功", { type: "success" });
  });
};
provide("sync", sync);
provide("get", get);

// 定时器引用
type TimerRef = ReturnType<typeof setInterval>;
let autoRefreshIntervalId: TimerRef | null = null;

onMounted(() => {
  autoRefreshIntervalId = setInterval(
    () => {
      get();
    },
    3 * 60 * 1000
  );
});

onBeforeUnmount(() => {
  if (autoRefreshIntervalId !== null) {
    clearInterval(autoRefreshIntervalId);
    autoRefreshIntervalId = null;
  }
});

const windowWidth = ref(window.innerWidth);

const updateWidth = () => {
  windowWidth.value = window.innerWidth;
};

onMounted(() => {
  window.addEventListener("resize", updateWidth);
});

onUnmounted(() => {
  window.removeEventListener("resize", updateWidth);
});
</script>
<style scoped lang="scss">
@import url("./styles/detail.scss");
</style>
